package com.ssm.sport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ssm.sport.entity.Shipping;
import com.ssm.sport.mapper.ShippingMapper;
import com.ssm.sport.service.ShippingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 收货地址服务实现类
 */
@Service
public class ShippingServiceImpl implements ShippingService {

    @Autowired
    private ShippingMapper shippingMapper;

    @Override
    @Transactional
    public Integer add(Integer userId, Shipping shipping) {
        if (userId == null || shipping == null) {
            return null;
        }
        
        // 设置用户ID
        shipping.setUserId(userId);
        
        // 如果设置为默认地址，需要将其他地址设为非默认
        boolean isDefault = shipping.getDefaultStatus() != null && shipping.getDefaultStatus() == 1;
        
        // 设置默认值
        if (shipping.getDefaultStatus() == null) {
            // 查询用户是否有收货地址，如果没有则设为默认
            QueryWrapper<Shipping> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            Long countValue = shippingMapper.selectCount(queryWrapper);
            int count = countValue != null ? countValue.intValue() : 0;
            shipping.setDefaultStatus(count == 0 ? 1 : 0);
        }
        
        // 设置创建和更新时间
        Date now = new Date();
        shipping.setCreateTime(now);
        shipping.setUpdateTime(now);
        
        // 保存收货地址
        try {
            shippingMapper.insert(shipping);
        } catch (Exception e) {
            return null;
        }
        
        // 如果设置为默认地址，需要更新其他地址为非默认
        if (isDefault) {
            updateOtherShippingToNonDefault(userId, shipping.getId(), now);
        }
        
        return shipping.getId();
    }

    @Override
    @Transactional
    public boolean delete(Integer userId, Integer shippingId) {
        if (userId == null || shippingId == null) {
            return false;
        }
        
        QueryWrapper<Shipping> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("id", shippingId);
        
        Shipping shipping = shippingMapper.selectOne(queryWrapper);
        if (shipping == null) {
            return false;
        }
        
        int result = shippingMapper.delete(queryWrapper);
        
        // 如果删除的是默认地址，需要重新设置一个默认地址
        if (result > 0 && Objects.equals(shipping.getDefaultStatus(), 1)) {
            setNewDefaultAddressAfterDelete(userId);
        }
        
        return result > 0;
    }

    @Override
    @Transactional
    public boolean update(Integer userId, Shipping shipping) {
        if (userId == null || shipping == null || shipping.getId() == null) {
            return false;
        }
        
        // 确保更新的是用户自己的地址
        shipping.setUserId(userId);
        
        QueryWrapper<Shipping> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", shipping.getId()).eq("user_id", userId);
        
        // 检查地址是否存在
        Shipping existShipping = shippingMapper.selectOne(queryWrapper);
        if (existShipping == null) {
            return false;
        }
        
        // 设置更新时间
        shipping.setUpdateTime(new Date());
        
        int result = shippingMapper.update(shipping, queryWrapper);
        
        // 如果更新成功，处理默认地址逻辑
        if (result > 0) {
            // 如果设置为默认地址，需要更新其他地址为非默认
            if (shipping.getDefaultStatus() != null && shipping.getDefaultStatus() == 1) {
                updateOtherShippingToNonDefault(userId, shipping.getId(), shipping.getUpdateTime());
            }
            // 如果取消默认地址，需要设置其他地址为默认
            else if (shipping.getDefaultStatus() != null && shipping.getDefaultStatus() == 0 && 
                    existShipping.getDefaultStatus() != null && existShipping.getDefaultStatus() == 1) {
                setNewDefaultAddressAfterDelete(userId);
            }
        }
        
        return result > 0;
    }

    @Override
    public Shipping getById(Integer userId, Integer shippingId) {
        if (userId == null || shippingId == null) {
            return null;
        }
        
        QueryWrapper<Shipping> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("id", shippingId);
        return shippingMapper.selectOne(queryWrapper);
    }

    @Override
    public List<Shipping> getByUserId(Integer userId) {
        if (userId == null) {
            return Collections.emptyList();
        }
        return shippingMapper.selectByUserId(userId);
    }

    @Override
    public Shipping getDefaultShipping(Integer userId) {
        if (userId == null) {
            return null;
        }
        return shippingMapper.selectDefaultShipping(userId);
    }

    @Override
    @Transactional
    public boolean setDefault(Integer userId, Integer shippingId) {
        if (userId == null || shippingId == null) {
            return false;
        }
        
        // 先验证地址是否存在
        QueryWrapper<Shipping> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("id", shippingId);
        Shipping shipping = shippingMapper.selectOne(queryWrapper);
        
        if (shipping == null) {
            return false;
        }
        
        // 已经是默认地址，无需更新
        if (Objects.equals(shipping.getDefaultStatus(), 1)) {
            return true;
        }
        
        // 使用自定义方法一步完成操作
        int result = shippingMapper.setDefault(userId, shippingId);
        
        return result > 0;
    }
    
    /**
     * 将用户其他收货地址设为非默认
     * 
     * @param userId 用户ID
     * @param currentShippingId 当前收货地址ID
     * @param updateTime 更新时间
     */
    private void updateOtherShippingToNonDefault(Integer userId, Integer currentShippingId, Date updateTime) {
        UpdateWrapper<Shipping> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId)
                    .ne("id", currentShippingId)
                    .set("default_status", 0)
                    .set("update_time", updateTime);
        shippingMapper.update(null, updateWrapper);
    }
    
    /**
     * 删除默认地址后设置新的默认地址
     * 
     * @param userId 用户ID
     */
    private void setNewDefaultAddressAfterDelete(Integer userId) {
        QueryWrapper<Shipping> findOneQuery = new QueryWrapper<>();
        findOneQuery.eq("user_id", userId).orderByDesc("create_time").last("LIMIT 1");
        
        Shipping lastShipping = shippingMapper.selectOne(findOneQuery);
        if (lastShipping != null) {
            lastShipping.setDefaultStatus(1);
            lastShipping.setUpdateTime(new Date());
            shippingMapper.updateById(lastShipping);
        }
    }
} 